package com.eastcom.mystope.daemon.provider;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.eastcom.mystope.common.util.SpringContextProvider;
import com.eastcom.mystope.daemon.config.DbInfo;
import com.eastcom.mystope.daemon.config.Table;
import com.eastcom.mystope.daemon.context.ServerContext;
import com.eastcom.mystope.daemon.extern.db.config.DstResource;
import com.eastcom.mystope.daemon.extern.db.config.Record;
import com.eastcom.mystope.daemon.extern.db.config.SrcResource;
import com.eastcom.mystope.daemon.extern.db.config.Task;
import com.eastcom.mystope.daemon.extern.db.context.TaskContext;
import com.eastcom.mystope.daemon.extern.file.parse.txt.config.FileContext;


public class DbContextProvider{
	private static Log logger = LogFactory.getLog(DbContextProvider.class);
	public boolean loadDbSource(String dbName,String tbName){
		DbEngine dbEngine = (DbEngine) SpringContextProvider.getBean("dbEngine");
		ServerContext.setCustomerType(dbName);
		boolean result = dbEngine.getTableInfo(dbName, tbName);
		logger.debug("ffffffffff"+result);
		return result;
	}

	public DbInfo reGetDbInfo(String fileName) throws JAXBException{
		File file = new File("database/"+fileName);
		if(! file.exists()){
			return null;
		}
		JAXBContext ctx = JAXBContext.newInstance(DbInfo.class);
		Unmarshaller unmarshaller = ctx.createUnmarshaller();
		DbInfo dbInfo = (DbInfo) unmarshaller.unmarshal(file);
		return dbInfo;
	}

	public boolean getDbInfo(Task task, Record record){
		//获取目的数据库表结构
		List<DstResource> dstResourceList = record.getDstResourceConfig().getDstResource();
		logger.debug(dstResourceList);
		List<SrcResource> srcResourceList = record.getSrcResourceConfig().getSrcResource();
		logger.debug(srcResourceList);
		List<DbInfo> dbNeedRewrite = new ArrayList<DbInfo>();
		for(DstResource dstResource : dstResourceList){
			String dbName = dstResource.getDbNameString().trim();
			String tbName = dstResource.getTbNameString().trim();
			String fileName = dbName+".xml";
			logger.debug("sdffsdfs"+fileName);

			try {
				DbInfo dbInfo = reGetDbInfo(fileName);
				logger.debug(dbInfo);
				if(dbInfo == null || !dbInfo.getTables().containsKey(tbName)){
					if(loadDbSource(dbName,tbName)){
						logger.debug(ServerContext.dbMap.get(dbName));
						dbNeedRewrite.add(ServerContext.dbMap.get(dbName));
					}
				}else{
					ServerContext.dbMap.put(dbName, dbInfo);
				}
			} catch (JAXBException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
				return false;
			}
		}

		for(SrcResource srcResource : srcResourceList){
			logger.debug(srcResource);
			String dbName = srcResource.getDbNameString().trim();
			if(srcResource.getTbNameString() == null){
				continue;
			}
			String tbName = srcResource.getTbNameString().trim();
			String fileName = dbName+".xml";
			logger.debug("sdffsdfs"+fileName);
			try {
				DbInfo dbInfo = reGetDbInfo(fileName);
				logger.debug(dbInfo);
				if(dbInfo == null || !dbInfo.getTables().containsKey(tbName)){
					if(loadDbSource(dbName,tbName)){
						logger.debug(ServerContext.dbMap.get(dbName));
						dbNeedRewrite.add(ServerContext.dbMap.get(dbName));
					}
				}else{
					ServerContext.dbMap.put(dbName, dbInfo);
				}

			} catch (JAXBException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
				return false;
			}
		}
		try {
			for(DbInfo dbIf: dbNeedRewrite){
				writeDbInfo(dbIf.getName()+".xml",dbIf);
			}
		} catch (IOException e1) {
			// TODO 自动生成的 catch 块
			e1.printStackTrace();
			return false;
		}
		return true;
	}

	public void writeDbInfo(String fileName, DbInfo dbInfo) throws IOException{
		File context = new File("database");
		if(! context.isDirectory()){
			context.mkdirs();
		}
		try {
			JAXBContext ctx = JAXBContext.newInstance(DbInfo.class);
			Marshaller marchaller = ctx.createMarshaller();
			File file = new File("database/"+fileName);
			if(! file.exists()){
				file.createNewFile();
			}
			FileWriter fileWriter = new FileWriter(file);
			marchaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marchaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
			marchaller.marshal(dbInfo, fileWriter);
		} catch (JAXBException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} 
	}


	public static void main(String[] args) throws IOException {
		//		new DbContextProvider().writeDbInfoToFile();

	}
}
